/**
 * FtpDataSource.java
 * @author: liuex
 * 2007-12-29 ����09:44:38
 *
 * note: 
 */
package lex.mtd.core.net;

import java.io.IOException;
import java.io.InputStream;

import org.lex.net.ftp.IFTPClient;
import org.lex.net.ftp.util.FTPClientFactory;

import lex.mtd.core.utils.DaemonExecutor;

public class FTPDataSource implements DataSource
{
	private static final int RETRY_COUNT = 10;
	private IFTPClient ftp = null;
	private String directory = null;
	private String file = null;
	private long seek = 0L;

	public FTPDataSource( IFTPClient ftp, String dir, String file )
	{
		this.ftp = ftp;
		this.directory = dir;
		this.file = file;
	}

	@Override
	public String getURL()
	{
		return ftp.getURL().toString();
	}

	@Override
	public void close()
	{
		DaemonExecutor.execute( new Runnable(){
			@Override
			public void run()
			{
				abort();
				FTPClientFactory.getDefaultFactory().close( ftp );
			}
		} );
	}

	@Override
	public InputStream openInputStream() throws IOException
	{
		if( false == ftp.pwd().equals( this.directory ) )
			ftp.cwd( this.directory );
		ftp.restart( seek );
		return ftp.get( file );
	}

	@Override
	public long getContentLength( long seek ) throws IOException
	{
		this.seek = seek;
		String pwd = ftp.pwd();
		if( false == pwd.equals( this.directory ) )
			ftp.cwd( this.directory );
		long len = ftp.size( file );
		return len;
	}

	private boolean abort()
	{
		int i = 0;
		while( i < RETRY_COUNT )
		{
			try
			{
				this.ftp.abort();
				return true;
			}
			catch( IOException e )
			{
				e.printStackTrace();
			}
			i++;
			try
			{
				Thread.sleep( 100 );
			}
			catch( Exception e )
			{
				e.printStackTrace();
			}
		}
		return false;
	}
}
